package net.lainiao;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;

/**
 * Created by Administrator on 2016/11/10.
 */
public class CreateClientExample {
    public static final String PATH="/CreateClientExample/basic";

    public static void main(String[] args) throws Exception {
        TestingServer server=new TestingServer();
        CuratorFramework client=null;
        try {
            client=createSimple(server.getConnectString());
            client.start();
            client.create().creatingParentsIfNeeded().forPath(PATH,"test".getBytes());
            CloseableUtils.closeQuietly(client);
            client=createWithOptions(server.getConnectString(),new ExponentialBackoffRetry(1000,3),1000,1000);
            client.start();
            System.out.println(new String(client.getData().forPath(PATH)));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseableUtils.closeQuietly(client);
            CloseableUtils.closeQuietly(server);
        }
    }

    private static CuratorFramework createWithOptions(String connectString, ExponentialBackoffRetry exponentialBackoffRetry, int connectionTimeoutMs, int sessionTimeoutMs) {
        return CuratorFrameworkFactory.builder().connectString(connectString).retryPolicy(exponentialBackoffRetry).connectionTimeoutMs(connectionTimeoutMs).sessionTimeoutMs(sessionTimeoutMs).build();
    }

    private static CuratorFramework createSimple(String connectString) {
        ExponentialBackoffRetry retryPolicy=new ExponentialBackoffRetry(1000,3);
        return CuratorFrameworkFactory.newClient(connectString,retryPolicy);
    }
}
